package LunaServer.routing;

import com.google.gson.Gson;
import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

/**
 * 路由接口，所有路由处理器都需要实现此接口
 */
public interface Route {
    /**
     * 处理HTTP请求
     * 
     * @param exchange HttpExchange对象，包含请求和响应信息
     * @return 响应内容字符串
     * @throws IOException IO异常
     */
    String handleRequest(HttpExchange exchange) throws IOException;

    /**
     * 处理404未找到路径的情况
     */
    default String handleNotFound(HttpExchange exchange) throws IOException {
        Map<String, Object> errorResult = new HashMap<>();
        errorResult.put("code", "404");
        errorResult.put("error", "Not Found");
        errorResult.put("time", Instant.now().toString());
        Gson gson = new Gson();
        String response = gson.toJson(errorResult);
        exchange.getResponseHeaders().set("Content-Type", "application/json");
        exchange.sendResponseHeaders(404, response.getBytes(StandardCharsets.UTF_8).length);

        OutputStream os = exchange.getResponseBody();
        os.write(response.getBytes(StandardCharsets.UTF_8));
        os.close();
        return response;
    }

    /**
     * 处理405方法不允许的情况
     */
    default String handleMethodNotAllowed(HttpExchange exchange) throws IOException {
        Map<String, Object> errorResult = new HashMap<>();
        errorResult.put("code", "405");
        errorResult.put("error", "Method Not Allowed");
        errorResult.put("time", Instant.now().toString());
        Gson gson = new Gson();
        String response = gson.toJson(errorResult);
        exchange.getResponseHeaders().set("Content-Type", "application/json");
        exchange.sendResponseHeaders(405, response.getBytes(StandardCharsets.UTF_8).length);

        OutputStream os = exchange.getResponseBody();
        os.write(response.getBytes(StandardCharsets.UTF_8));
        os.close();
        return response;
    }
}